package com.serviceprovider.business.module.user.validators;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.admin.user.services.dao.interfaces.IUserService;
import com.serviceprovider.business.module.user.model.impl.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.validation.Errors;

//~--- JDK imports ------------------------------------------------------------

import java.util.regex.Pattern;

@Repository(value = "userRegistrationValidator")
public class UserRegistrationValidator implements org.springframework.validation.Validator {
    private String mailRegEx =
        "(^$|^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\\-+)|([A-Za-z0-9]+\\.+)|([A-Za-z0-9]+\\++))*[A-Za-z0-9]+@((\\w+\\-+)|(\\w+\\.))*\\w{1,63}\\.[a-zA-Z]{2,6}$)";
    @Autowired
    protected IUserService userService;

    @Override
    public boolean supports(Class validateClass) {

        // TODO Auto-generated method stub
        return User.class.equals(validateClass);
    }

    @Override
    public void validate(Object user, Errors errors) {
        User tmpUser = (User) user;

        if ((tmpUser.getFirstName() == null) || (tmpUser.getFirstName().trim().length() < 1)) {
            errors.rejectValue("firstName", "registration.validation.no_first_name");
        }

        if ((tmpUser.getLastName() == null) || (tmpUser.getLastName().trim().length() < 1)) {
            errors.rejectValue("lastName", "registration.validation.no_last_name");
        }

        if ((tmpUser.getEmail() == null) || (tmpUser.getEmail().trim().length() < 1)) {
            errors.rejectValue("email", "registration.validation.no_email");
        } else if (userService.getByEmail(tmpUser.getEmail().trim()) != null) {
            errors.rejectValue("email", "registration.validation.repeat_email");
        } else {
            Pattern pattern = Pattern.compile(mailRegEx);

            if (!pattern.matches(mailRegEx, tmpUser.getEmail().trim())) {
                errors.rejectValue("email", "registration.validation.invalid_mail");
            }
        }

        if (tmpUser.getSsn() == null) {
            errors.rejectValue("ssn", "registration.validation.no_ssn");
        } else if (userService.getBySSN(tmpUser.getSsn()) != null) {
            errors.rejectValue("ssn", "registration.validation.repeat_ssn");
        }

        if ((tmpUser.getPassword() == null) || (tmpUser.getPassword().trim().length() < 1)) {
            errors.rejectValue("password", "registration.validation.no_password");
        } else if (tmpUser.getPassword().length() < 6) {
            errors.rejectValue("password", "registration.validation.password_length");
        }
    }
}



